#include "UsrAI.h"
#include<set>
#include <iostream>
#include<unordered_map>
#include<cmath>
#include"Coordinate.h"
#include"Map.h"
using namespace std;
tagGame tagUsrGame;
ins UsrIns;
//
//
#define RESOURCE_MEAT 1
#define FARMER_MAXNUM 20  //第二阶段村民人数上限
#define SHIP_MAXNUM 10    //第二阶段战船人数上限

//一次性判断

bool isFirstUpdate = true;  // 标记是否为首次更新
bool stage2=false;   //第二阶段
bool grannydone=false; //谷仓建成
bool marketdone=false;//市场建成
bool wood_upgrade=false; //砍树技术升级
bool ship_ready=false; //战舰准备
bool duijiaostrategy=false;//对角策略
bool stage3=false; //第三阶段
bool coastdone=false;//敌方海岸线探索完毕
bool locktrans=false;
bool kaoan=false;
bool qicheng=false;//运输船启程
bool escape_tran=false;
bool escape_tran_2=false;
bool arrow_up=false;
bool beizhan=false;//士兵备战，可以战斗
bool upgrade_riderdef=false;//骑士防御升级
bool upgrade_tool=false;
bool upgrade_stone=true;
bool upgrade_indef=false;
bool upgrade_archdef=false;
bool upgrade_CLUBMAN=false;
bool init=false;
bool tempt=false;
bool tempt_accident=false;
bool tempt_accident_deal=false;
bool tempt_begin=false;
bool tempt_site=false;
bool tempt_doing=false;
bool tempt_done=false;
bool find_gold=false;
bool stage4=false;
bool lockport=false;
bool shifasite=false;
bool upgrade_gold=false;
bool goldminer=false;
bool needsave_1=false;//运输船保护


double startdr=0,startur=0;
int dissn=0;
int enddr=0,endur=0;//停船地点
int tempdr=0,tempur=0;//诱惑地点
int farmermax=0;
int transn=0; //第三阶段运人
int noenemyframe=0;//没有敌人
int ddr=0,dur=0;
int tempt_cool_time=0;//诱杀冷却
int tempt_count=0;

vector<int> buildingtect;//检查建筑是否完成
void building_undone(const tagInfo& info){
    buildingtect.clear();
    for(tagBuilding build:info.buildings){
        bool flag=false;
        if(build.Percent==0){
            for(tagFarmer farmer :info.farmers){
                if(farmer.WorkObjectSN==build.SN){
                    flag=true;
                }
            }
            if(!flag){
                buildingtect.push_back(build.SN);
            }

        }
    }
}

vector<int> enemysn;//遇见敌人总数
vector<int> enemybuildsn;//箭塔总数
vector<int> attractsn;//诱敌人数

// 当前活跃侦察骑士的SN
static int activeScoutSN = 0;

static bool visited[128][128]={false};

// 地图状态与资源宏定义（完全贴合文档表3、表6）
#define TERRAIN_UNKNOWN -2    // 未知区域（MAPPATTERN_UNKNOWN）
#define TERRAIN_OCEAN   -1    // 海洋（MAPPATTERN_OCEAN）

// 128x128地图数组
static int mapGrid[128][128];
static bool mapInitialized = false;

// 初始化地图
void initMap() {
    for (int dr = 0; dr < 128; ++dr) {
        for (int ur = 0; ur < 128; ++ur) {
            mapGrid[dr][ur] = TERRAIN_UNKNOWN;
        }
    }
    mapInitialized = true;
}

// 更新地图（处理2×2资源），未处理建筑和新的树
void updateMap(const tagInfo& info) {
    if (!mapInitialized) initMap();

    //  先更新地形
    for (int dr = 0; dr < 128; ++dr) {
        for (int ur = 0; ur < 128; ++ur) {
                if ((*info.theMap)[dr][ur].type == MAPPATTERN_OCEAN) {
                    mapGrid[dr][ur] = TERRAIN_OCEAN;
                } else {
                    mapGrid[dr][ur] = (*info.theMap)[dr][ur].height; // 陆地高度
                }

        }
    }

    // 更新资源（2×2资源覆盖4个格子）
    for (const auto& res : info.resources) {
        int dr = res.BlockDR;    // 资源左下角坐标
        int ur = res.BlockUR;
        if (dr < 0 || dr >= 128 || ur < 0 || ur >= 128) continue;

        // 判断是否为2×2资源
        bool is2 = (res.Type == RESOURCE_STONE ||
                      res.Type == RESOURCE_GOLD ||
                      res.Type == RESOURCE_FISH);

        if (is2) {
            // 2×2资源：覆盖4个格子（左下角为基准点）
            for (int dx = 0; dx < 2; ++dx) {
                for (int dy = 0; dy < 2; ++dy) {
                    int x = dr + dx;
                    int y = ur + dy;
                    if (x < 128 && y < 128) {
                        mapGrid[x][y] = res.Type; // 所有格子标记为同一资源类型
                    }
                }
            }
        } else {
            // 1×1资源：仅覆盖单个格子
            mapGrid[dr][ur] = res.Type;
        }
    }
}

// 全局映射表：key=目标SN（资源/建筑的SN），value=正在操作该目标的村民SN列表
static unordered_map<int, vector<int>> targetToFarmersMap;
// 更新映射表：根据村民当前工作状态，同步目标与村民的对应关系
void updateTargetFarmersMap(const vector<tagFarmer>& farmers) {
    // 先清空旧数据
    targetToFarmersMap.clear();

    // 遍历所有村民，记录工作中的村民与目标的对应关系
    for (const auto& farmer : farmers) {
        // 只处理「工作中」的村民（排除空闲/移动等状态）
        if (farmer.NowState != HUMAN_STATE_WORKING) {
            continue;
        }

        // 目标SN（资源或建筑的SN，即村民正在操作的对象）
        int targetSN = farmer.WorkObjectSN;

        // 将村民SN添加到对应目标的列表中
        targetToFarmersMap[targetSN].push_back(farmer.SN);
    }
}
// 通过目标SN查询正在操作该目标的村民SN列表
vector<int> getFarmersByTargetSN(int targetSN) {
    // 若目标不存在于映射表中，返回空列表
    if (targetToFarmersMap.find(targetSN) == targetToFarmersMap.end()) {
        return {};
    }
    // 返回该目标对应的村民列表
    return targetToFarmersMap[targetSN];
}
// 查询操作指定目标的村民数量
int getFarmerCountByTargetSN(int targetSN) {
    // 查找目标是否存在于映射表中
    auto it = targetToFarmersMap.find(targetSN);
    if (it == targetToFarmersMap.end()) {
        return 0; // 目标不存在，返回0
    }
    // 返回该目标对应的村民列表长度（即数量）
    return it->second.size();
}
// 检查目标是否已达最大操作人数
bool isTargetFull(int targetSN, int maxWorkers) {
    vector<int> currentWorkers = getFarmersByTargetSN(targetSN);
    return currentWorkers.size() >= maxWorkers;
}

static int buildingCounts[11] = {0}; //最多11种建筑
//更新建筑计数（每帧调用一次）
void updateBuildingCounts(const std::vector<tagBuilding>& buildings) {
    // 重置计数
    for (int i = 0; i < 11; i++) buildingCounts[i] = 0;
    // 统计每种建筑数量
    for (const auto& b : buildings) {
        if (b.Type >= 0 && b.Type < 11) {
            buildingCounts[b.Type]++;
        }
    }
}
//目标建筑数量
int getBuildingCount(int type) {
    return buildingCounts[type];
}

// 全局资源映射表（SN -> 资源指针）
static unordered_map<int, const tagResource*> resourceMap;
// 每帧更新资源映射表
void updateResourceMap(const vector<tagResource>& resources) {
    resourceMap.clear();
    for (const auto& res : resources) {
        resourceMap[res.SN] = &res;
    }
}

// 我方大陆坐标列表（仅开局更新一次）
vector<pair<int, int>> ourLandCoords;
// 敌方大陆坐标列表（每帧更新，自动添加未在我方列表中的陆地）
vector<pair<int, int>> enemyLandCoords;
//海洋探索
vector<pair<int, int>> disocean;
//海岸线
static vector<pair<int, int>> coastline;
// 检查坐标是否在我方大陆列表中
bool InenemyLand(int& dr,int& ur) {
    for (const auto& c : enemyLandCoords) {
        if (c.first == dr && c.second== ur) {
            return true;
        }
    }
    return false;
}
// 检查坐标是否在我方大陆列表中
bool isCoordInOurLand(const pair<int, int>& coord) {
    for (const auto& c : ourLandCoords) {
        if (c == coord) {
            return true;
        }

    }
    return false;
}
//新海洋
bool isocean(int& dr,int& ur) {
    for (const auto& c : disocean) {
        if (c.first == dr && c.second== ur) {
            return true;
        }
    }
    return false;
}


// 每帧更新地形数据，自动分类陆地坐标
void updatelandMap( const tagInfo& info) {
    // 遍历地图中所有坐标
    for (int i = 0; i < 128; i++) {
        for (int j = 0; j < 128; j++) {
            // 获取当前坐标的地形类型
            int terrainType = (*info.theMap)[i][j].type;
            pair<int, int> coord = {i, j};

            // 仅处理陆地类型
            if (terrainType ==MAPPATTERN_GRASS) {
                // 首次更新时，将所有陆地添加到我方列表
                if (isFirstUpdate) {
                    ourLandCoords.push_back(coord);
                }
                // 非首次更新时，检查是否在我方列表中，排除重复计入
                else if (!isCoordInOurLand(coord) && !InenemyLand(coord.first,coord.second)) {
                    // 不在我方列表中，自动添加到敌方列表
                    enemyLandCoords.push_back(coord);
                }
            }

            if(terrainType ==MAPPATTERN_OCEAN){
                if(!isocean(i,j)){
                    disocean.push_back(coord);
                }
            }
        }
    }

    // 首次更新后标记为false
    if (isFirstUpdate) {
        isFirstUpdate = false;
    }
}
bool findEnemyLand() {
    return (enemyLandCoords.size()!=0);
}
// 全局村民工作统计函数
struct FarmerWorkStats {
    int idle = 0;
    int boat=0;    //空闲渔船
    int food = 0;
    int fishman = 0;
    int fishboat =0;  //工作渔船
    int transboat=0;
    int intrans=0;
    int wood = 0;
    int stone = 0;
    int gold = 0;
    int building = 0;
    int total=0;     //总人数
    int totalboat=0;   //总渔船数
    int totalfarm=0;    //总运输船数
};
// 统计村民工作
FarmerWorkStats countFarmerJobs(const vector<tagFarmer>& farmers) {
    FarmerWorkStats stats;

    for (const auto& f : farmers) {
        if(f.FarmerSort==2){
            stats.totalboat++;
        }
        else if(f.FarmerSort==1){
            stats.transboat++;
        }
        else if(f.FarmerSort==0){
            stats.totalfarm++;
        }
        stats.total++;

        if (f.NowState == HUMAN_STATE_IDLE) {
            if(f.FarmerSort==2)
                stats.boat++;
            else if(f.FarmerSort==1){
                stats.intrans++;
            }
            else stats.idle++;
            continue;
        }

        if (f.NowState != HUMAN_STATE_WORKING) {
            continue; // 跳过非工作状态的村民
        }

        auto it = resourceMap.find(f.WorkObjectSN);
        if (it == resourceMap.end()) {
            continue; // 找不到对应资源，跳过
        }

        const tagResource* res = it->second;

        // 根据农民类型和资源类型分类统计
        switch (f.FarmerSort) {
            case 0: // 陆地生产单位
                switch (res->Type) {
                    case RESOURCE_GAZELLE: stats.food++; break;
                    case RESOURCE_FISH:    stats.fishman++; break;
                    case RESOURCE_TREE:    stats.wood++; break;
                    case RESOURCE_STONE:   stats.stone++; break;
                    case RESOURCE_GOLD:    stats.gold++; break;
                    default:               stats.building++; break;
                }
                break;
            case 1: // 运输船
                 stats.intrans++;

            case 2: // 渔船
                stats.fishboat++;
                break;

            default: break;
        }
    }
    cout<<stats.total<<' '<<stats.idle<<' '<<stats.totalfarm<<' '<<stats.food<<' '<<stats.wood<<' '<<stats.boat<<' '<<stats.fishboat<<' '<<stats.transboat<<endl;
    return stats;
}

// 军队统计结构体，用于统计不同类型军队的数量、状态等
struct ArmyStats {
    int total = 0;          // 军队总数量
    int idle = 0;           // 闲置（未执行任务）的军队数量
    int clubman = 0;        // 棍棒兵数量
    int slinger = 0;        // 投石兵数量
    int swordsman = 0;      // 战斧兵数量
    int bowman = 0;         // 弓兵数量
    int scout = 0;          // 侦察骑兵数量
    int ship = 0;           // 战船数量
    // 可扩展其他状态，比如作战中、移动中、待命等
    int attacking = 0;       // 正在作战的军队数量
};
// 统计军队状态、类型等信息
ArmyStats countArmyTypes(const vector<tagArmy>& armies) {
    ArmyStats stats;

    for (const auto& army : armies) {
        stats.total++;

        // 先根据状态统计通用状态（闲置、作战中、移动中等）
        if (army.NowState == HUMAN_STATE_IDLE) {  //
            stats.idle++;
        } else if (army.NowState ==HUMAN_STATE_ATTACKING ) {
            stats.attacking++;
        }
        // 根据军队类型（sort）统计具体兵种数量
        switch (army.Sort) {
            case AT_CLUBMAN:
                stats.clubman++;
                break;
            case AT_SLINGER:
                stats.slinger++;
                break;
            case AT_SWORDSMAN:
                stats.swordsman++;
                break;
            case AT_BOWMAN:
                stats.bowman++;
                break;
            case AT_SCOUT:
                stats.scout++;
                break;
            case AT_SHIP:
                stats.ship++;
                break;
            default:
                // 若有未知类型，可在这里处理，比如打印日志
                break;
        }
    }

    // 打印统计信息（可根据需求调整输出格式）
    cout << stats.total << ' ' <<stats.idle <<' ' << stats.ship <<' '<< stats.bowman << endl;
    return stats;
}

// 记录区域内的资源统计
struct ResourceDensity {
    int
    totalCount; // 资源总数量（累加所有资源的Cnt）
    int area;    // 区域面积（格子数）
    int density; // 密集度（totalCount / area）
    int centerDR;   // 区域中心坐标
    int centerUR;
};

// 计算以(centerDR, centerUR)为中心，size x size范围内的资源密集度
ResourceDensity calculateResourceDensity(const tagInfo& info, int resourceType, int centerDR, int centerUR, int size) {
    ResourceDensity density;
    density.centerDR = centerDR;
    density.centerUR = centerUR;
    density.totalCount = 0;

    // 计算区域边界（确保不超出地图范围）
    int startDR = max(0, centerDR - size/2); // 左边界
    int endDR = min(127, centerDR + size/2); // 右边界（地图最大127）
    int startUR = max(0, centerUR - size/2); // 下边界
    int endUR = min(127, centerUR + size/2); // 上边界

    // 遍历区域内的所有资源
    for (const auto& res : info.resources) {
        // 只统计目标类型的有效资源（如羚羊、树木）
        if (res.Type != resourceType || res.Cnt <= 0) {
            continue;
        }

        // 检查资源是否在目标区域内
        if (res.BlockDR >= startDR && res.BlockDR <= endDR &&
            res.BlockUR >= startUR && res.BlockUR <= endUR) {
            density.totalCount += res.Cnt; // 累加资源数量
        }
    }

    // 计算区域面积（格子数）
    density.area = (endDR - startDR + 1) * (endUR - startUR + 1);
    // 计算密集度
    density.density = (density.area > 0) ? (density.totalCount / density.area) : 0;
    return density;}
// 寻找指定资源类型的最密集区域（以每个资源点为中心计算）
ResourceDensity findMostDenseArea(const tagInfo& info, int resourceType, int searchSize) {
    ResourceDensity maxDensity;
    maxDensity.density = -1; // 初始化为最小值，表示未找到

    // 以每个资源点为中心计算密集度
    for (const auto& res : info.resources) {
        if (res.Type != resourceType || res.Cnt <= 0) {
            continue;
        }
        // 计算以当前资源为中心的searchSize x searchSize区域的密集度
        ResourceDensity current = calculateResourceDensity(
            info, resourceType, res.BlockDR, res.BlockUR, searchSize
        );

        // 更新最大密集度区域
        if (current.density > maxDensity.density) {
            maxDensity = current;
        }
    }

    return maxDensity;
}

//寻找最近资源
tagResource* findNearestResource(const vector<tagResource>& resources, int type, double dr, double ur) {
    if (resources.empty()) {
        return nullptr; // 资源列表为空时直接返回空
    }
    tagResource* nearestResource = nullptr;
    double minDistance = 1e9; // 初始化一个极大值作为最小距离阈值
    for (auto& resource : resources) {
        if(type==RESOURCE_MEAT){
            if(resource.Type != RESOURCE_GAZELLE&&resource.Type != RESOURCE_FISH )
                continue;
        }
        else {
            if(resource.Type != type)
            continue;
        }
        if (resource.Cnt <= 0) {
            continue;
        }
        double distance = calculateDistance(resource.DR, resource.UR, dr, ur);
        if (distance < minDistance) {
            minDistance = distance;
            nearestResource = const_cast<tagResource*>(&resource); // 去除const属性以返回可操作指针
        }
    }

    return nearestResource;
}
// 寻找最近资源(考虑负载)
tagResource* findOptimalResource(
    const vector<tagResource>& resources,
    const vector<int>& resourceTypes,
    double dr, double ur,
    int maxFarmersPerResource
) {
    // 筛选资源并排序（与之前相同）
    vector<pair<const tagResource*, double>> validResources;
    for (const auto& resource : resources) {
        for (int type : resourceTypes) {
            if (resource.Type == type && resource.Cnt > 0) {
                double distance = calculateDistance(dr, ur, resource.DR, resource.UR);
                validResources.push_back({&resource, distance});
                break;
            }
        }
    }
    using ResourceDistancePair = pair<const tagResource*, double>;
    if (validResources.empty()) return nullptr;
    sort(validResources.begin(), validResources.end(),
         [](const ResourceDistancePair& a, const ResourceDistancePair& b) { return a.second < b.second; });

    // 只检查负载，不检查路径
    for (const auto& pair : validResources) {
        const tagResource* resourcePtr = pair.first;
        if (!isTargetFull(resourcePtr->SN, maxFarmersPerResource)) {
            return const_cast<tagResource*>(resourcePtr);
        }
    }

    return const_cast<tagResource*>(validResources[0].first);
}



//计算两点距离
double calculateDistance(double dr1, double ur1, double dr2, double ur2) {
    return sqrt(pow(dr1 - dr2, 2) + pow(ur1 - ur2, 2));
}

//检查当前资源情况（用于判断）
bool pdEnoughResources(const tagInfo& info, int wood=0, int meat=0, int stone=0, int gold=0) {
    return (info.Wood >= wood) &&(info.Meat >= meat) &&(info.Stone >= stone) &&  (info.Gold >= gold);
}


// 寻找合适的建筑位置
bool findValidBuildLocation(const tagInfo& info, int buildingType, int originDR, int originUR, int& resultBlockDR, int& resultBlockUR) {
    int size = 3; // 默认3x3
    if (buildingType == BUILDING_ARROWTOWER || buildingType == BUILDING_DOCK ||buildingType == BUILDING_HOME) {
        size = 2; // 2x2建筑
    }
     int SEARCH_RADIUS = 30;
     if(buildingType==BUILDING_HOME){
         SEARCH_RADIUS = 40;
     }
    // 螺旋搜索：从内向外逐层检查
    for (int layer = 0; layer <= SEARCH_RADIUS; layer++) {
        // 中心点（仅第一层）
        if (layer == 0) {
            int blockDR = originDR;
            int blockUR = originUR;

            // 计算实际左下角坐标（3x3建筑以中心为锚点）
            int actualDR = blockDR;
            int actualUR = blockUR;
            if (size == 3) {
                actualDR = blockDR - 1; // 3x3建筑的左下角是中心格左下方一格
                actualUR = blockUR - 1;
            }

            // 检查边界
            if (actualDR < 0 || actualDR > 127 - size + 1 || actualUR < 0 || actualUR > 127 - size + 1) {
                continue;
            }

            // 检查合法性
            if (isLocationValid(info, buildingType, actualDR, actualUR, size)) {
                resultBlockDR = actualDR;
                resultBlockUR = actualUR;
                return true;
            }
            continue;
        }

        // 螺旋层的四条边：右、上、左、下
        // 右边（从上到下）
        for (int dy = -layer; dy < layer; dy++) {
            int blockDR = originDR + layer;
            int blockUR = originUR + dy;

            // 计算实际左下角坐标
            int actualDR = blockDR;
            int actualUR = blockUR;
            if (size == 3) {
                actualDR = blockDR - 1;
                actualUR = blockUR - 1;
            }

            if (actualDR < 0 || actualDR > 127 - size + 1 || actualUR < 0 || actualUR > 127 - size + 1) {
                continue;
            }

            if (isLocationValid(info, buildingType, actualDR, actualUR, size)) {
                resultBlockDR = actualDR;
                resultBlockUR = actualUR;
                return true;
            }
        }

        // 上边（从右到左）
        for (int dx = layer; dx > -layer; dx--) {
            int blockDR = originDR + dx;
            int blockUR = originUR + layer;

            // 计算实际左下角坐标
            int actualDR = blockDR;
            int actualUR = blockUR;
            if (size == 3) {
                actualDR = blockDR - 1;
                actualUR = blockUR - 1;
            }

            if (actualDR < 0 || actualDR > 127 - size + 1 || actualUR < 0 || actualUR > 127 - size + 1) {
                continue;
            }

            if (isLocationValid(info, buildingType, actualDR, actualUR, size)) {
                resultBlockDR = actualDR;
                resultBlockUR = actualUR;
                return true;
            }
        }

        // 左边（从下到上）
        for (int dy = layer; dy > -layer; dy--) {
            int blockDR = originDR - layer;
            int blockUR = originUR + dy;

            // 计算实际左下角坐标
            int actualDR = blockDR;
            int actualUR = blockUR;
            if (size == 3) {
                actualDR = blockDR - 1;
                actualUR = blockUR - 1;
            }

            if (actualDR < 0 || actualDR > 127 - size + 1 || actualUR < 0 || actualUR > 127 - size + 1) {
                continue;
            }

            if (isLocationValid(info, buildingType, actualDR, actualUR, size)) {
                resultBlockDR = actualDR;
                resultBlockUR = actualUR;
                return true;
            }
        }

        // 下边（从左到右）
        for (int dx = -layer; dx < layer; dx++) {
            int blockDR = originDR + dx;
            int blockUR = originUR - layer;

            // 计算实际左下角坐标
            int actualDR = blockDR;
            int actualUR = blockUR;
            if (size == 3) {
                actualDR = blockDR - 1;
                actualUR = blockUR - 1;
            }

            if (actualDR < 0 || actualDR > 127 - size + 1 || actualUR < 0 || actualUR > 127 - size + 1) {
                continue;
            }

            if (isLocationValid(info, buildingType, actualDR, actualUR, size)) {
                resultBlockDR = actualDR;
                resultBlockUR = actualUR;
                return true;
            }
        }
    }

    // 未找到合法地址
    return false;
}


// 检查单个位置的合法性
bool isLocationValid(const tagInfo& info, int buildingType, int blockDR, int blockUR, int size) {
    // 检查是否为已探索区域
    for (int dr = 0; dr < size; dr++) {
        for (int ur = 0; ur < size; ur++) {
            int checkDR = blockDR + dr;
            int checkUR = blockUR + ur;
            if (checkDR >= 128 || checkUR >= 128 ||
                (*info.theMap)[checkDR][checkUR].type == MAPPATTERN_UNKNOWN) {
                return false;

            }
        }
    }

    // 检查地形是否符合建筑要求
    bool flag=false;
    if (buildingType == BUILDING_DOCK) {
            // 船坞特殊逻辑：2x2区域必须全为海洋，且至少1个相邻格子是浅滩

            for (int dr = 0; dr < size; dr++) {
                for (int ur = 0; ur < size; ur++) {
                    int checkDR = blockDR + dr;
                    int checkUR = blockUR + ur;
                    if ((*info.theMap)[checkDR][checkUR].type != MAPPATTERN_OCEAN) {
                        return false;

                    }
                }
            }

            // 检查船坞周围8个方向是否有浅滩（扩大搜索范围，确保边缘位置也能检测到）
            const int dirs[8][2] = {{-1,1}, {-1,0}, {0,-1},
                                    {1,-1},          {0,2},
                                    {1,2},  {2,0}, {2,1}};
            for (auto& dir : dirs) {
                int checkDR = blockDR + dir[0];
                int checkUR = blockUR + dir[1];
                // 边界内检查
                if (checkDR >= 0 && checkDR < 128 && checkUR >= 0 && checkUR < 128) {
                    if ((*info.theMap)[checkDR][checkUR].type == MAPPATTERN_GRASS) {
                        flag=true;
                    }
                }
            }
            if(!flag)return false;
    }
         else {
        // 陆地建筑需确保整个范围内均为草地
        for (int dr = 0; dr < size; dr++) {
            for (int ur = 0; ur < size; ur++) {
                int checkDR = blockDR + dr;
                int checkUR = blockUR + ur;
                if (checkDR >= 128 || checkUR >= 128 ||
                    (*info.theMap)[checkDR][checkUR].type != MAPPATTERN_GRASS) {
                    return false;

                }
            }
        }
        int baseHeight = (*info.theMap)[blockDR][blockUR].height;
        for (int dr = -1; dr <size+1; dr++) {
            for (int ur =-1; ur <size+1; ur++) {
                int checkDR = blockDR + dr;
                int checkUR = blockUR + ur;
                if (checkDR >= 128 || checkUR >= 128 ||
                    (*info.theMap)[checkDR][checkUR].height != baseHeight) {
                    return false;
                }
            }

        }
    }

    // 检查是否与资源重叠
    for (const auto& res : info.resources) {

           // 默认1x1，特殊资源单独处理
              int resMaxDR = res.BlockDR;
              int resMaxUR = res.BlockUR;
              int resMinDR = res.BlockDR;
              int resMinUR = res.BlockUR;



              // 特殊处理：渔场,石头，金子(2x2)
              if (res.Type == RESOURCE_FISH) {
                  resMaxDR += 1;  // 扩展到2x2
                  resMaxUR += 1;
              }
              if (res.Type==RESOURCE_STONE || res.Type==RESOURCE_GOLD) {
                  resMaxDR += 2;  // 扩展到2x2
                  resMaxUR += 2;
                  resMinDR -= 1;
                  resMinUR -= 1;
              }

              // 检查建筑与资源是否重叠
              bool overlaps = !(blockDR + size <= resMinDR||  // 建筑在资源左侧
                                resMaxDR < blockDR ||              // 资源在建筑左侧
                                blockUR + size <= resMinUR ||  // 建筑在资源下方
                                resMaxUR < blockUR);              // 资源在建筑下方

              if (overlaps) {
                  return false;  // 存在重叠，不能放置
              }

       }


    // 检查是否与已有建筑重叠
    for (const auto& building : info.buildings) {
        int buildingSize = (building.Type == BUILDING_HOME || building.Type == BUILDING_ARROWTOWER || building.Type == BUILDING_DOCK) ? 3 : 4;
        size++;
        if (!(blockDR + size <= building.BlockDR ||
              blockDR >= building.BlockDR + buildingSize ||
              blockUR + size <= building.BlockUR ||
              blockUR >= building.BlockUR + buildingSize)) {
            return false;
        }
    }
    //检查是否与村民重叠
    for (const auto& f : info.farmers) {
        if((f.BlockDR >= blockDR && f.BlockDR < blockDR + size) &&
                       (f.BlockUR >= blockUR && f.BlockUR < blockUR + size) ) {
            return false;
        }

}
return true;
}

// 从已知陆地找周围的黑格子
vector<pair<int, int>> findNearbyBlackGrids(const tagInfo& info,vector<pair<int, int>> landcoords,int searchRange = 10) {
    vector<pair<int, int>> blackGrids;

    // 遍历所有已知敌方陆地格子
    for (auto& land : landcoords) {
        int x = land.first;
        int y = land.second;
         // 搜索陆地周围的范围
        // 搜索陆地周围searchRange范围内的格子
        for (int dx = -searchRange; dx <= searchRange; dx++) {
            for (int dy = -searchRange; dy <= searchRange; dy++) {
                int nx = x + dx;
                int ny = y + dy;

                // 检查边界
                if (nx < 0 || nx >= 128 || ny < 0 || ny >= 128) continue;

                // 只记录黑格子（未知区域）
                if ((*info.theMap)[nx][ny].type == MAPPATTERN_UNKNOWN) {
                    blackGrids.push_back({nx, ny});
                }
            }
        }
    }

    return blackGrids;
}

// 从黑格子附近找可移动的海格子
pair<int, int> findWaternearBlack(const tagInfo& info, const vector<pair<int, int>>& blackGrids, tagHuman &ship) {
    if (blackGrids.empty()) return {-1, -1};

    // 存储黑格子附近的海格子
    vector<pair<int, int>> candidateWaters;

    for (auto& black : blackGrids) {
        int x = black.first;
        int y = black.second;

        // 检查黑格子周围1格内的海格子
        for (int dx = -1; dx <= 1; dx++) {
            for (int dy = -1; dy <= 1; dy++) {
                int nx = x + dx;
                int ny = y + dy;

                if (nx < 0 || nx >=128 || ny < 0 || ny >= 128) continue;
                if ((*info.theMap)[nx][ny].type == MAPPATTERN_OCEAN) {
                    candidateWaters.push_back({nx, ny});
                }
            }
        }
    }

    if (candidateWaters.empty()) return {-1, -1};

    // 选择离战舰最近的海格子
    pair<int, int> nearest = candidateWaters[0];
    int minDist = abs(nearest.first - ship.BlockDR) + abs(nearest.second - ship.BlockUR);

    for (auto& water : candidateWaters) {
        int dist = abs(water.first - ship.BlockDR) + abs(water.second - ship.BlockUR);
        if (dist < minDist) {
            nearest = water;
            minDist = dist;
        }
    }

    return nearest;
}

// 从黑格子附近找可移动的陆地格子
pair<int, int> findlandnearBlack(const tagInfo& info, const vector<pair<int, int>>& blackGrids, tagArmy &army) {
    if (blackGrids.empty()) return {-1, -1};

    // 存储黑格子附近的陆地格子
    vector<pair<int, int>> candidatelands;

    for (auto& black : blackGrids) {
        int x = black.first;
        int y = black.second;

        // 检查黑格子周围1格内的陆地格子
        for (int dx = -1; dx <= 1; dx++) {
            for (int dy = -1; dy <= 1; dy++) {
                int nx = x + dx;
                int ny = y + dy;

                if (nx < 0 || nx >=128 || ny < 0 || ny >= 128) continue;
                if ((*info.theMap)[nx][ny].type == MAPPATTERN_GRASS) {
                    candidatelands.push_back({nx, ny});
                }
            }
        }
    }

    if (candidatelands.empty()) return {-1, -1};

    // 选择离战舰最近的陆地格子
    pair<int, int> nearest = candidatelands[0];
    int minDist = abs(nearest.first - army.BlockDR) + abs(nearest.second - army.BlockUR);

    for (auto& land : candidatelands) {
        int dist = abs(land.first - army.BlockDR) + abs(land.second - army.BlockUR);
        if (dist < minDist) {
            nearest = land;
            minDist = dist;
        }
    }

    return nearest;
}

// 全局变量：记录每艘船的上一位置和卡死计数
static unordered_map<int, pair<int, int>> lastPos;    // 船ID -> (x, y)
static unordered_map<int, int> stuckCount;                 // 船ID -> 卡死帧数

// 存储三个待探索的角落坐标
vector<pair<int,int>> cornerTargets;
int currentTargetIndex = 0;


// 查找运输船附近的海岸线（返回最近的一个）
bool findCoastNearTransport(tagInfo& info, int transDR, int transUR, int& coastBlockDR, int& coastBlockUR, int& ddr,int& dur) {
    // 定义搜索范围
    const int SEARCH_RANGE = 5;
    int minDist = SEARCH_RANGE * SEARCH_RANGE;
    bool found = false;

    // 遍历搜索范围内的所有区块
    for (int dr = max(0, transDR - SEARCH_RANGE); dr <= min(127, transDR + SEARCH_RANGE); dr++) {
        for (int ur = max(0, transUR - SEARCH_RANGE); ur <= min(127, transUR + SEARCH_RANGE); ur++) {
            bool hasdock=false;
            for(tagBuilding& dock:info.buildings){
                if((dock.BlockDR==dr||dock.BlockDR+1==dr)&&(dock.BlockUR==ur||dock.BlockUR+1==ur)){
                    hasdock=true;
                    break;
                }
            }
            if(hasdock)continue;
            // 定义方向数组，用于检查相邻格子
            const int dx[] = {-1, 1, 0, 0};
            const int dy[] = {0, 0, -1, 1};

            for (int i = 0; i < 4; ++i) {
                int newDR = dr + dx[i];
                int newUR = ur + dy[i];

                // 检查边界
                if (newDR < 0 || newDR >= 128 || newUR < 0 || newUR >= 128) continue;

                // 判断是否为海岸线
                if ((*info.theMap)[dr][ur].type == MAPPATTERN_OCEAN && (*info.theMap)[newDR][newUR].type == MAPPATTERN_GRASS) {
                    int distSq = (dr - transDR) * (dr - transDR) + (ur - transUR) * (ur - transUR);
                    if (distSq < minDist) {
                        minDist = distSq;
                        coastBlockDR = dr;
                        coastBlockUR = ur;
                        found = true;
                        ddr=dx[i];
                        dur=dy[i];
                    }
                    break; // 一旦确定是海岸线，无需再检查其他相邻格子
                }
            }
        }
    }

    return found;
}
//上运输船的对象
vector<int> carrier;

// 提取已知大陆的海岸线
vector<pair<int, int>> getCoastlines(const vector<pair<int, int>>& enemyLand, const tagInfo& info) {
    vector<pair<int, int>> coasts;
    for (const auto& coord : enemyLand) {
        int dr = coord.first, ur = coord.second;
        // 四方向有海洋即为海岸线
        if ((dr > 0 && (*info.theMap)[dr-1][ur].type == MAPPATTERN_OCEAN) ||
            (dr < 127 && (*info.theMap)[dr+1][ur].type == MAPPATTERN_OCEAN) ||
            (ur > 0 &&(*info.theMap)[dr][ur-1].type == MAPPATTERN_OCEAN) ||
            (ur < 127 && (*info.theMap)[dr][ur+1].type == MAPPATTERN_OCEAN)) {
            coasts.push_back(coord);
        }
    }
    return coasts;
}

// 从现有海岸线中找到第一个长度≥2的连续块，返回其中间格子
pair<int, int> getAnyMiddleCoastBlock(const vector<pair<int, int>>& coastlines) {
    if (coastlines.empty()) return {-1, -1}; // 无效标记

    set<pair<int, int>> coastSet(coastlines.begin(), coastlines.end());
    set<pair<int, int>> processed;

    for (const auto& start : coastlines) {
        if (processed.count(start)) continue;

        int dr = start.first;
        int ur = start.second;



        // 检查横向连续（≥2格）
        vector<pair<int, int>> horizontal;
        int currUR = ur;
        while (coastSet.count({dr, currUR})) {
            horizontal.emplace_back(dr, currUR);
            currUR++;
        }
        if (horizontal.size() >= 2) {
            int midIndex = horizontal.size() / 2;
            return horizontal[midIndex]; // 直接返回横向连续块的中点
        }

        // 检查纵向连续（≥2格）
        vector<pair<int, int>> vertical;
        int currDR = dr;
        while (coastSet.count({currDR, ur})) {
            vertical.emplace_back(currDR, ur);
            currDR++;
        }
        if (vertical.size() >= 2) {
            int midIndex = vertical.size() / 2;
            return vertical[midIndex]; // 直接返回纵向连续块的中点
        }

        // 标记单个格子为已处理
        processed.insert(start);
    }

    // 没有找到≥2格的连续块
    return {-1, -1};
}


// 计算格子(dr, ur)到最近海岸线的距离
int getDistanceToCoast(int dr, int ur, const vector<pair<int, int>>& coastlines) {
    int minDist = INT_MAX;
    for (const auto& coast : coastlines) {
        int dist = abs(dr - coast.first) + abs(ur - coast.second); // 曼哈顿距离
        minDist = min(minDist, dist);
    }
    return minDist;
}

// 辅助函数
bool IsCoordInMap(int dr, int ur) {
    return dr >= 0 && dr < 128 && ur >= 0 && ur < 128;
}

// 用mapGrid判断是否为外层金矿
bool IsGridOuterGold(int dr, int ur) {
    // 检查上下左右是否有可站立的非金矿格子
    const int dirs[4][2] = {{-1,0}, {1,0}, {0,-1}, {0,1}};
    for (auto& d : dirs) {
        int chkDR = dr + d[0], chkUR = ur + d[1];
        if (IsCoordInMap(chkDR, chkUR)) {
            int neighbor = mapGrid[chkDR][chkUR];
            if (neighbor != RESOURCE_GOLD && neighbor<=4 && neighbor>=0) {
                return true;
            }
        }
    }
    return false;
}

// 通过格子坐标找金矿SN（适配2×2资源）
int GetGoldSNByGrid(int dr, int ur, const vector<tagResource>& resources) {
    for (const auto& res : resources) {
        if (res.Type != RESOURCE_GOLD) continue;
        // 2×2资源范围判断
        if (dr >= res.BlockDR && dr < res.BlockDR + 2 &&
            ur >= res.BlockUR && ur < res.BlockUR + 2) {
            return res.SN;
        }
    }
    return -1;
}


// 在指定坐标附近范围内，找外层金矿SN（存于vector）
vector<int> GetNearbyOuterGoldSNs(int centerDR, int centerUR, int radius, const tagInfo& info) {
    vector<int> result;
    if (!mapInitialized || radius <= 0) return result;

    set<int> uniqueSNs; // 去重

    // 遍历地图中指定范围内的格子
    for (int dr = centerDR - radius; dr <= centerDR + radius; ++dr) {
        for (int ur = centerUR - radius; ur <= centerUR + radius; ++ur) {
            // 跳过地图外或非金矿的格子
            if (!IsCoordInMap(dr, ur) || mapGrid[dr][ur] != RESOURCE_GOLD) {
                continue;
            }

            // 是外层金矿 → 找对应资源SN
            if (IsGridOuterGold(dr, ur)) {
                // 从资源列表中匹配该金矿的SN（利用2×2资源特性）
                int sn = GetGoldSNByGrid(dr, ur, info.resources);
                if (sn != -1) {
                    uniqueSNs.insert(sn);
                }
            }
        }
    }

    // 转换为vector返回
    result.assign(uniqueSNs.begin(), uniqueSNs.end());
    return result;
}

// 全局map：键为战舰SN，值为是否已前往事故发生地
static map<int, bool> tempt_accident_ship;

// 标记战舰
void marktemptship(int shipSN) {
    // 仅对首次登岸的村民初始化（未在map中记录过）
    if (tempt_accident_ship.find(shipSN) ==tempt_accident_ship.end()) {
        tempt_accident_ship[shipSN] = false; // 初始状态：未前往

    }
}



void UsrAI::processData()
{
    tagInfo info = getInfo();
    // 更新建筑计数
    updateBuildingCounts(info.buildings);
    // 每帧更新资源映射表
    updateResourceMap(info.resources);
    // 统计村民工作
    FarmerWorkStats stats = countFarmerJobs(info.farmers);
    // 统计军队状态、类型等信息
    ArmyStats armystats= countArmyTypes(info.armies);
    //分配任务
    updateTargetFarmersMap(info.farmers);
    //更新敌我大陆
     updatelandMap(info);
    //更新地图
     updateMap(info);
     // 提取已知大陆的海岸线
     coastline = getCoastlines(enemyLandCoords, info);
     //检查未完成的建筑
      building_undone(info);

     //两个点
     if(enddr!=0 && !tempt_done ){
             for (auto& coast : coastline) {
                 int max_dist=0;
                 int dist = abs(coast.first - enddr) + abs(coast.second - endur); // 曼哈顿距离
                 if(dist>max_dist && dist<=100){
                     tempdr=coast.first;
                     tempur=coast.second;
                     max_dist=dist;
                 }
             }

     }




     //统计在敌方大陆的村民人数
     if(!goldminer){
         int inenemyfarmer=0;
         for(tagFarmer farm:info.farmers){
             if(InenemyLand(farm.BlockDR,farm.BlockUR)){
                 inenemyfarmer++;
             }
         }
         //人够了
         if(inenemyfarmer>=18){
             goldminer=true;
             DebugText("人够了");
         }
     }



     //运人
     if(beizhan && !goldminer){
         //来回运人(一艘船)
         for(tagFarmer transport :info.farmers){
             //运输船
             if(transport.SN==transn && transport.NowState==HUMAN_STATE_IDLE ){
                 // 基于单一方向计算目标位置
                 static double tagdr = (enddr + 0.5) * BLOCKSIDELENGTH;
                 static double tagur = (endur + 0.5) * BLOCKSIDELENGTH;

                 if(!shifasite){
                     HumanMove(transport.SN,startdr,startur);
                     shifasite=true;
                     DebugText("前达始发点");
                     break;
              }

                 if (transport.Resource == 5){
                     // 到达后基于同一方向微调
                     if (transport.Resource==5 && info.GameFrame%10==0) {
                         tagdr+=2*ddr;
                         tagur+=2*dur;
                         DebugText("偏移");
                         HumanMove(transport.SN,tagdr,tagur);

                     }
                     // 发送移动命令
                     HumanMove(transport.SN, tagdr, tagur);
                 }

                 int dist=abs(transport.BlockDR-enddr)+abs(transport.BlockUR-endur);
                 if(transport.Resource==0 && dist<5){
                     shifasite = false;
                     tagdr = (enddr + 0.5) * BLOCKSIDELENGTH;
                     tagur = (endur + 0.5) * BLOCKSIDELENGTH;
                     DebugText("送完"+to_string(transn));
                     DebugText(to_string(carrier.size()));
                     carrier.clear();
                     DebugText("清空carrier");
                 }
                 if(abs(transport.DR-startdr)+abs(transport.UR-startur)<BLOCKSIDELENGTH && transport.Resource==0 && !shifasite){
                      shifasite = true;
                      DebugText("准备上船");
                 }
             }
        }
     }





    // 第一阶段：石器时代（新的分配方式还没试过）
     //送的仓库
     static tagBuilding stock1;
     if(getBuildingCount(BUILDING_STOCK)==1){
     for (const auto& building : info.buildings) {
         if (building.Type == BUILDING_STOCK) {
             stock1=building;
             break;
         }
     }
     }
     //常用的市中心
     tagBuilding centersite;
     for (const auto& building : info.buildings) {
         if (building.Type == BUILDING_CENTER) {
             centersite=building;
             break;
         }
     }

     // 记录仓库2位置
     static tagBuilding stock2;
     if(getBuildingCount(BUILDING_STOCK)==2){
     for (const tagBuilding& building : info.buildings) {
         if (building.Type == BUILDING_STOCK && building.SN!= stock1.SN) {
             stock2 = building;
             break;
         }
     }
     }
     //谷仓
     tagBuilding gucang;
     for (const auto& building : info.buildings) {
         if (building.Type == BUILDING_GRANARY) {
             gucang=building;
             if(building.Percent==100){
               grannydone=true;
             }
             break;
         }
     }
     //市场
     for (const auto& building : info.buildings) {
         if (building.Type == BUILDING_MARKET) {
             if(building.Percent==100){
               marketdone=true;
             }
             break;
         }
     }

     if(info.civilizationStage == 1 || !stage2) {

         for ( auto& farmer : info.farmers) {

            // 跳过非空闲村民
            if (farmer.NowState != HUMAN_STATE_IDLE ) {
                continue;
            }
            if(farmer.FarmerSort!=0){
                continue;
            }
            tagFarmer* idleFarmer = const_cast<tagFarmer*>(&farmer);
            //未完成建筑
            if(!buildingtect.empty()){
                HumanAction(idleFarmer->SN,buildingtect[0]);
                break;
            }

            // piror1: 建造房屋
            if (getBuildingCount(BUILDING_HOME) < 2 && info.civilizationStage == 1) {
                if (info.Wood >= BUILD_HOUSE_WOOD) {

                    // 寻找建造位置
                    int houseDR, houseUR;
                    if (findValidBuildLocation(info, BUILDING_HOME, centersite.BlockDR,centersite.BlockUR, houseDR, houseUR)) {
                        if (idleFarmer) {
                            HumanBuild(idleFarmer->SN, BUILDING_HOME, houseDR, houseUR);
                            DebugText("建造第一间房屋");
                            continue; // 任务完成，跳过后续逻辑
                        }
                    }
                }
            }

            // piror2: 建造仓库
            if (getBuildingCount(BUILDING_STOCK) < 2 && info.civilizationStage == 1 && info.Wood >= BUILD_STOCK_WOOD ) {
                // 寻找羚羊资源最密集的区域
                ResourceDensity denseArea = findMostDenseArea(info, RESOURCE_GAZELLE, 10);

                // 游戏初期阶段建造一间仓库
                if (denseArea.density > 0) { // 找到有效密集区域
                    // 以密集区中心为原点，寻找仓库建造位置
                    int stockDR, stockUR;
                    if (findValidBuildLocation(info, BUILDING_STOCK, denseArea.centerDR, denseArea.centerUR, stockDR, stockUR)) {
                        if (idleFarmer) {
                            HumanBuild(idleFarmer->SN, BUILDING_STOCK, stockDR, stockUR);
                            DebugText("在羚羊最密集区建造仓库（密度：" + to_string(denseArea.density) + "）");
                            continue; // 任务完成，跳过后续逻辑
                        }
                    } else {
                        DebugText("未找到合适位置建造仓库（密集区坐标：" +
                                  to_string(denseArea.centerDR) + "," +
                                  to_string(denseArea.centerUR) + "）");
                    }
                } else {
                    DebugText("未找到羚羊资源密集区，尝试常规建造");
                }
            }


            // piror3: 建造船坞
            if (getBuildingCount(BUILDING_STOCK) > 1 && getBuildingCount(BUILDING_DOCK) < 1 && info.Wood >= BUILD_DOCK_WOOD) {
                tagResource* nearestfish = findNearestResource(info.resources, RESOURCE_FISH, idleFarmer->DR, idleFarmer->UR);
                if (nearestfish == nullptr) {
                    DebugText("未找到鱼群，无法建造船坞");
                } else {
                    int dockDR, dockUR;
                    if (findValidBuildLocation(info, BUILDING_DOCK, nearestfish->BlockDR, nearestfish->BlockUR, dockDR, dockUR)) {
                        HumanBuild(idleFarmer->SN, BUILDING_DOCK, dockDR, dockUR);
                        DebugText("建造船坞（村民SN：" + to_string(idleFarmer->SN) + "）");
                        continue; // 任务完成，跳过后续逻辑
                    } else {
                        DebugText("鱼群附近无合法船坞位置");
                    }
                }
            }




            // piror4: 资源采集逻辑
            if (idleFarmer) {
                tagResource* nearestgazelle = findOptimalResource(info.resources, {RESOURCE_GAZELLE}, idleFarmer->DR, idleFarmer->UR,2);
                tagResource* nearesttree =findOptimalResource(info.resources, {RESOURCE_TREE}, idleFarmer->DR, idleFarmer->UR,2);


                // 肉类不足
                if (info.Meat < 500 && stats.food < 4 && nearestgazelle ) {
                     if (nearestgazelle) {
                        HumanAction(idleFarmer->SN, nearestgazelle->SN);
                    }
                    continue;
                }

                // 木材常规补充
                if (nearesttree != nullptr) {
                    HumanAction(idleFarmer->SN, nearesttree->SN);
                    continue;
                }
            }

        }

        // 如果市镇中心空闲，且有足够的食物，且农民数量小于人口上限，则生产农民(预留两艘船)
        for (tagBuilding& building : info.buildings) {
            if (building.Type == BUILDING_CENTER && building.Project == 0 &&
                info.Meat >= BUILDING_CENTER_CREATEFARMER_FOOD &&
                stats.totalfarm < info.Human_MaxNum-3) {
                BuildingAction(building.SN, BUILDING_CENTER_CREATEFARMER);
                break;
            }
        }

        // 建造渔船
        for (tagBuilding& building : info.buildings) {
            if (building.Type == BUILDING_DOCK && building.Project == 0 &&
                info.Wood >= BUILDING_DOCK_CREATE_SAILING_WOOD && stats.totalboat<3) {
                BuildingAction(building.SN, BUILDING_DOCK_CREATE_SAILING);
                break;
            }
        }
    }


    // 如果市镇中心空闲，且有足够的食物，升级时代
    for (tagBuilding& building : info.buildings) {
        if (building.Type == BUILDING_CENTER && building.Project == 0 &&
             info.civilizationStage == 1 && info.Meat >= 500 ) {
            BuildingAction(building.SN, BUILDING_CENTER_UPGRADE);
            break;
        }
    }
    //捕鱼不要停
    for(tagFarmer& boat : info.farmers){
            if(boat.FarmerSort==2 && boat.NowState==0){
                tagResource* fish =findNearestResource(info.resources, RESOURCE_FISH ,boat.DR, boat.UR);
                if(fish!=nullptr){
                HumanAction(boat.SN,fish->SN);
                }
                if(fish==nullptr){
                    // 从已知敌方陆地周围找黑格子
                    auto blackGrids = findNearbyBlackGrids(info,ourLandCoords,4);
                    if (blackGrids.empty()) break;
                    // 找黑格子附近的可移动海格子
                    auto target = findWaternearBlack(info, blackGrids,boat);
                    if (target.first == -1){
                        break;
                    }
                    HumanMove(boat.SN,(target.first+0.5)*BLOCKSIDELENGTH, (target.second+0.5)*BLOCKSIDELENGTH);
                    continue;

                }
            }
        }

    // 第二阶段：海战

    if(info.civilizationStage == 2 && !stage3) {
        stage2=true;
            for (const auto& farmer : info.farmers){
                if (farmer.NowState != HUMAN_STATE_IDLE) {
                    continue;
                }
                if(farmer.FarmerSort!=0){
                    continue;
                }
                tagFarmer* idleFarmer =const_cast<tagFarmer*>(&farmer);
                if(idleFarmer!=nullptr){
                    //未完成建筑
                    if(!buildingtect.empty()){
                        HumanAction(idleFarmer->SN,buildingtect[0]);
                        break;
                    }

                   //  建造船坞
                    if (getBuildingCount(BUILDING_STOCK) > 1 && getBuildingCount(BUILDING_DOCK) < 2 && info.Wood >= BUILD_DOCK_WOOD ) {
                        tagResource* nearestfish = findNearestResource(info.resources, RESOURCE_FISH, idleFarmer->DR, idleFarmer->UR);
                        if (nearestfish == nullptr) {
                            DebugText("未找到鱼群，无法建造船坞");
                        } else {
                            int dockDR, dockUR;
                            if (findValidBuildLocation(info, BUILDING_DOCK, nearestfish->BlockDR, nearestfish->BlockUR, dockDR, dockUR)) {
                                HumanBuild(idleFarmer->SN, BUILDING_DOCK, dockDR, dockUR);
                                DebugText("建造船坞（村民SN：" + to_string(idleFarmer->SN) + "）");
                                continue; // 任务完成，跳过后续逻辑
                            } else {
                                DebugText("鱼群附近无合法船坞位置");
                            }
                        }
                    }
                //piror1:建谷仓，建市场，升级砍树技术
                    if(getBuildingCount(BUILDING_GRANARY) < 1&& info.Wood >= BUILD_GRANARY_WOOD ){
                        int granaryDR,granaryUR;
                        if (findValidBuildLocation(info, BUILDING_GRANARY, centersite.BlockDR, centersite.BlockUR, granaryDR ,granaryUR)) {
                                HumanBuild(idleFarmer->SN, BUILDING_GRANARY, granaryDR,granaryUR);
                                DebugText("建造第一间谷仓");
                                continue;
                        }
                        else{
                            DebugText("没有找到合适的位置建造谷仓");
                        }
                    }

                    if(grannydone && info.Wood >= BUILD_MARKET_WOOD && getBuildingCount(BUILDING_MARKET)<1){
                        int marketDR,marketUR;
                        if (findValidBuildLocation(info, BUILDING_GRANARY, centersite.BlockDR, centersite.BlockUR,  marketDR,marketUR)) {
                                HumanBuild(idleFarmer->SN, BUILDING_MARKET,  marketDR,marketUR);
                                DebugText("建造第一间市场");
                                continue;
                        }
                        else{
                            DebugText("没有找到合适的位置建造市场");
                        }
                    }
                    if(marketdone && pdEnoughResources(info,BUILDING_MARKET_WOOD_UPGRADE_WOOD,BUILDING_MARKET_WOOD_UPGRADE_FOOD)){
                        for (tagBuilding& building : info.buildings) {
                            if (building.Type == BUILDING_MARKET && building.Project == 0 && pdEnoughResources(info,BUILDING_MARKET_WOOD_UPGRADE_WOOD,BUILDING_MARKET_WOOD_UPGRADE_FOOD)) {
                                BuildingAction(building.SN, BUILDING_MARKET_WOOD_UPGRADE);
                                break;
                            }
                        }
                         wood_upgrade=true;

                    }

                //piror2:建房屋
                    if(getBuildingCount(BUILDING_HOME)<8 && stats.total+armystats.total>info.Human_MaxNum-8){   //10战船+17村民+3渔船
                        int centerDR = stock1.BlockDR, centerUR =stock1.BlockUR;
                        //在三屋以下（16 farmers）/市场建完升级技术后
                            if ((info.Wood >= BUILD_HOUSE_WOOD && getBuildingCount(BUILDING_HOME)<4)||(wood_upgrade && info.Wood >= BUILD_HOUSE_WOOD) ) {
                                // 寻找建造位置
                                int houseDR, houseUR;
                                if (findValidBuildLocation(info, BUILDING_HOME, centerDR, centerUR, houseDR, houseUR)) {
                                        HumanBuild(idleFarmer->SN, BUILDING_HOME, houseDR, houseUR);
                                        continue;

                          }

                    }
                    }


                //piror3:砍树
                    if(idleFarmer){
                        tagResource* nearesttree = findOptimalResource(info.resources, {RESOURCE_TREE}, idleFarmer->DR,idleFarmer->UR,2);
                        if(nearesttree!=nullptr)
                        HumanAction(idleFarmer->SN,nearesttree->SN);
                        continue;
                    }

            }
            }
            //造村民至上限
                if (centersite.Project == 0 && info.Meat >= BUILDING_CENTER_CREATEFARMER_FOOD && stats.total < 20) {
                    if((getBuildingCount(BUILDING_MARKET)<1 && stats.totalfarm<10) || wood_upgrade)
                    BuildingAction(centersite.SN, BUILDING_CENTER_CREATEFARMER);
                }


            //建战船，可考虑再建一船坞
                // 建造战船(市场建好)
                if(marketdone && info.Wood >BUILDING_DOCK_CREATE_SHIP_WOOD && !ship_ready){
                for (tagBuilding& building : info.buildings) {
                    if (building.Type == BUILDING_DOCK && building.Project == 0 &&info.Wood >= BUILDING_DOCK_CREATE_SHIP_WOOD && armystats.ship<SHIP_MAXNUM ) {
                        BuildingAction(building.SN,  BUILDING_DOCK_CREATE_SHIP);

                    }
                }
                }



        }

    //海战记录
        if(armystats.ship==SHIP_MAXNUM && !ship_ready){
            ship_ready=true;
            //海战开端
        }

        // 持续作战
        if(ship_ready && info.Wood >BUILDING_DOCK_CREATE_SHIP_WOOD && armystats.ship<6){
        for (tagBuilding& building : info.buildings) {
            if (building.Type == BUILDING_DOCK && building.Project == 0  ) {
                BuildingAction(building.SN,  BUILDING_DOCK_CREATE_SHIP);

            }
        }
        }




    //锁定敌舰，在战船数量达到最大值进攻
            tagArmy* enemy_army_ship = nullptr;
                for (tagArmy& enemy : info.enemy_armies) {
                    // 这里假设目标定为敌方战船
                    if (enemy.Sort == AT_SHIP && enemy.Blood>0) {
                        enemy_army_ship = &enemy;
                        break;
                    }

                }
                bool findenemyland=findEnemyLand();
               // 命令空闲的战船去对角,遇到敌舰或新大陆

                if(ship_ready && !enemy_army_ship && !findenemyland && !duijiaostrategy ){
                    for (tagArmy& army : info.armies) {
                        // 命令空闲的战船去对角
                        double tagdr=(127-centersite.BlockDR+0.5)*BLOCKSIDELENGTH,tagur=(127-centersite.BlockUR+0.5)*BLOCKSIDELENGTH;
                        if (army.Sort == AT_SHIP && army.NowState == HUMAN_STATE_IDLE) {
                            HumanMove(army.SN,tagdr,tagur);
                            if(army.DR==tagdr&&army.UR==tagur){
                                duijiaostrategy=true;
                            }
                            break;
                }
                    }

                }

                //备用策略
                if(ship_ready && !enemy_army_ship && !findenemyland && duijiaostrategy ){

                        if (cornerTargets.empty()) {
                            // 计算四个角落坐标
                            vector<pair<int, int>> allCorners = {
                                {0, 0},           // 左上角
                                {127, 0},         // 右上角
                                {0, 127},         // 左下角
                                {127, 127}        // 右下角
                            };

                            // 找到距离市中心最近的角落（本大陆所在角落）
                            double minDist =256;
                            int homeCornerIndex = 0;

                            for (int i = 0; i < 4; i++) {
                                int dist=abs(allCorners[i].first - centersite.BlockDR)+abs(allCorners[i].second - centersite.BlockUR);
                                if (dist < minDist) {
                                    minDist = dist;
                                    homeCornerIndex = i;
                                }
                            }
                            // 添加其他三个角落到目标列表
                            cornerTargets.clear();
                            for (int i = 0; i < 4; i++) {
                                if (i != homeCornerIndex) {
                                    cornerTargets.push_back({
                                        allCorners[i].first , allCorners[i].second });
                                }
                            }
                            }

                            // 遍历三个目标
                            if (currentTargetIndex < cornerTargets.size()) {
                                // 获取当前目标坐标
                                double tagdr = cornerTargets[currentTargetIndex].first;
                                double tagur = cornerTargets[currentTargetIndex].second;

                                // 派遣空闲战船
                                for (tagArmy& army : info.armies) {
                                    if (army.Sort == AT_SHIP && army.NowState == HUMAN_STATE_IDLE) {
                                        HumanMove(army.SN, tagdr, tagur);
                                        DebugText("战船前往目标: " + std::to_string((int)tagdr) + "," + std::to_string((int)tagur));
                                        if(army.DR==tagdr&&army.UR==tagur){
                                            currentTargetIndex++;
                                        }
                                        break;
                                    }
                                }


                }
                }


                // 如果有敌军战船，命令所有空闲的战船攻击敌军战船或骑士
                if (enemy_army_ship != nullptr) {
                    for (tagArmy& army : info.armies) {
                        if (army.Sort == AT_SHIP && army.NowState != HUMAN_STATE_ATTACKING) {
                            HumanAction(army.SN, enemy_army_ship->SN);
                            continue;
                        }
                    }
                }
                //找到敌方大陆，在安全的情况下探索
                if(findenemyland &&  !enemy_army_ship && info.GameFrame%5==0){
                    for(tagArmy& army:info.armies){
                        //跳过非战船
                        if(army.Sort!=AT_SHIP){
                            continue;
                        }
                        // 从已知敌方陆地周围找黑格子
                        auto blackGrids = findNearbyBlackGrids(info,enemyLandCoords);
                        if (blackGrids.empty()) break;
                        // 找黑格子附近的可移动海格子
                        auto target = findWaternearBlack(info, blackGrids,army);
                        if (target.first == -1){
                            coastdone=true;
                            break;
                        }
                        //移动战船
                        if (army.Sort == AT_SHIP && army.NowState == HUMAN_STATE_IDLE) {
                        HumanMove(army.SN,(target.first+0.5)*BLOCKSIDELENGTH, (target.second+0.5)*BLOCKSIDELENGTH);
                        continue;
                        }
                    }
                }




    //第三阶段：新大陆（真的不知道如何判定）
                tagArmy* enemy_army = nullptr;
                tagBuilding* enemy_building=nullptr;

                for(tagArmy& enemy : info.enemy_armies){
                    if(enemy.Sort!=AT_SHIP ){
                        auto it=find(enemysn.begin(),enemysn.end(),enemy.SN);
                        if(it==enemysn.end()){
                            enemysn.push_back(enemy.SN);
                        }
                        continue;
                    }
                }

                //战争
                //杀敌(先杀人，再打塔)
                for (tagArmy& enemy : info.enemy_armies) {
                    if (enemy.Sort != AT_SHIP && enemy.Blood>0) {
                        enemy_army = &enemy;
                        break;
                    }
                }

                for(tagBuilding build :info.enemy_buildings){
                    if(build.Type==BUILDING_ARROWTOWER && build.Blood>0){
                        enemy_building=&build;
                        break;
                    }
                }



                //推塔
                for(tagBuilding build :info.enemy_buildings){
                    auto it=find(enemybuildsn.begin(),enemybuildsn.end(),build.SN);
                    if(it==enemybuildsn.end()){
                          enemybuildsn.push_back(build.SN);
                    }
                    break;
                }


                //分配士兵工作



                if(info.GameFrame%5==0 && beizhan){

                        //正式开战
                            if (enemy_army != nullptr) {
                                for(tagArmy& army:info.armies){
                                        if ( army.NowState == HUMAN_STATE_IDLE ) {
                                            HumanAction(army.SN, enemy_army->SN);
                                            continue;
                                        }
                                }

                            }

                            if (enemy_building!=nullptr && enemy_army == nullptr){
                                DebugText("打塔"+to_string(enemy_building->SN));
                                for(tagArmy& army:info.armies){
                                    if (army.NowState == HUMAN_STATE_IDLE && army.Sort!=AT_SHIP) {
                                        HumanAction(army.SN, enemy_building->SN);
                                        continue;
                                    }
                                }

                            }

                            //备用方案(全图探索)
                            if( enemy_army==nullptr && enemy_building==nullptr){
                                for(tagArmy& army:info.armies){
                                    //跳过战船
                                    if(army.Sort==AT_SHIP){
                                        continue;
                                    }
                                    // 从已知敌方陆地周围找黑格子
                                    auto blackGrid = findNearbyBlackGrids(info,enemyLandCoords,3);
                                    if (blackGrid.empty()) break;
                                    // 找黑格子附近的可移动陆地格子
                                    auto target = findlandnearBlack(info, blackGrid,army);
                                    if (target.first == -1){
                                        break;
                                    }
                                    //移动士兵
                                    if (army.Sort != AT_SHIP && army.NowState == HUMAN_STATE_IDLE) {
                                    HumanMove(army.SN,(target.first+0.5)*BLOCKSIDELENGTH, (target.second+0.5)*BLOCKSIDELENGTH);
                                    continue;
                                    }
                                }
                        }


                }

                //箭塔打骑士先，再打其他
                for(tagBuilding tower:info.buildings){
                    if(tower.Type==BUILDING_ARROWTOWER ){
                        if(enemy_army!=nullptr){
                            int dist=abs(tower.BlockDR-enemy_army->BlockDR)+abs(tower.BlockUR-enemy_army->BlockUR);
                            if( dist<10){
                                HumanAction(tower.SN,enemy_army->SN);
                                continue;
                            }
                        }
                       }
                }

                    if(ship_ready && !stage4){
                    stage3=true;


                    //运输船靠岸，要改
                    for (const auto& transport : info.farmers){
                        if(transport.FarmerSort!=1){
                            continue;
                        }
                        if(transport.FarmerSort==1 && transn==0){
                            transn=transport.SN;
                        }

                        if(!kaoan){
                            int tdr,tur,ddr,dur;
                            if(findCoastNearTransport(info,transport.BlockDR,transport.BlockUR,tdr,tur,ddr,dur)){
                                startdr=(tdr+0.5+0.3*ddr)*BLOCKSIDELENGTH,startur=(tur+0.5+0.3*dur)*BLOCKSIDELENGTH;
                                kaoan=true;
                                HumanMove(transn,startdr,startur);
                                break;
                            }


                        }

                    }

                    //判断是否有建成的兵营
                    bool armycampdone=false;
                    for(tagBuilding camp:info.buildings){
                        if(camp.Type==BUILDING_ARMYCAMP&&camp.Percent==100){
                            armycampdone=true;
                            break;
                        }
                    }


                    //安排本土村民工作
                    for ( auto& f : info.farmers){
                        if(f.FarmerSort!=0){
                            continue;
                        }
                        if(InenemyLand(f.BlockDR,f.BlockUR)){
                            continue;
                        }

                        tagFarmer* idleFarmer=const_cast<tagFarmer*>(&f);
                        //强制上船（新）
                        auto it=find(carrier.begin(),carrier.end(),idleFarmer->SN);
                        if(kaoan && !qicheng && transn!=0 && it!=carrier.end()&& idleFarmer->WorkObjectSN!=transn){
                            HumanAction(idleFarmer->SN,transn);
                            DebugText(to_string(idleFarmer->SN));
                            DebugText("强制上船");
                            continue;
                        }

                        //空闲村民
                        if(idleFarmer->FarmerSort==0 && idleFarmer->NowState==HUMAN_STATE_IDLE){
                            //上运输船
                            if(transn!=0 && idleFarmer && carrier.size()<3 &&kaoan && !qicheng){
                                HumanAction(idleFarmer->SN,transn);
                                auto it=find(carrier.begin(),carrier.end(),idleFarmer->SN);
                                if(it!=carrier.end()){
                                    continue;
                                }
                                else{carrier.push_back(idleFarmer->SN);
                                DebugText(to_string(idleFarmer->SN)+"上船");
                                DebugText(to_string(carrier.size()));
                                for(tagFarmer s:info.farmers){
                                    if(s.SN==transn){
                                        DebugText(to_string(s.Resource));
                                    }
                                }
                                continue;
                                }
                            }

                            //建兵营
                            if(getBuildingCount(BUILDING_ARMYCAMP)<1 && info.Wood>BUILD_ARMYCAMP_WOOD){
                                int tdr,tur;
                                if(findValidBuildLocation(info, BUILDING_ARMYCAMP,idleFarmer->BlockDR,idleFarmer->BlockUR,tdr,tur) && info.Wood>=BUILD_ARMYCAMP_WOOD){
                                    HumanBuild(idleFarmer->SN,BUILDING_ARMYCAMP,tdr,tur);
                                    continue;
                                }
                                }


                            //造农场
                            if(getBuildingCount(BUILDING_FARM)<2 &&info.Wood>BUILD_FARM_WOOD && armycampdone){
                                int farmdr,farmur;
                                //在市中心或谷仓附近建农田
                                if (findValidBuildLocation(info, BUILDING_FARM,centersite.BlockDR,centersite.BlockUR,farmdr,farmur )) {

                                        HumanBuild(idleFarmer->SN, BUILDING_FARM, farmdr,farmur);
                                        DebugText("建造农场");
                                        continue;



                                }
                            }

                            //造房至11或12
                            if(info.Wood>BUILD_HOUSE_WOOD &&getBuildingCount(BUILDING_HOME)<12){
                                int houseDR, houseUR;
                                if( info.Wood>BUILD_HOUSE_WOOD && (getBuildingCount(BUILDING_HOME)<8 ||armycampdone)   ){
                                    if (findValidBuildLocation(info, BUILDING_HOME, stock2.BlockDR,stock2.BlockUR, houseDR, houseUR)||
                                           findValidBuildLocation(info, BUILDING_HOME, stock1.BlockDR,stock1.BlockUR, houseDR, houseUR) ) {
                                        if(!InenemyLand(houseDR,houseUR)){
                                            HumanBuild(idleFarmer->SN, BUILDING_HOME, houseDR, houseUR);
                                            continue;
                                        }
                                }
                            }
                            }

                            //备战后运人
                            if(beizhan){
                                 if(shifasite && carrier.size()<5){
                                     HumanAction(idleFarmer->SN,transn);
                                     auto it=find(carrier.begin(),carrier.end(),idleFarmer->SN);
                                     if(it!=carrier.end()){
                                         continue;
                                     }
                                     else{
                                         carrier.push_back(idleFarmer->SN);
                                         DebugText("上船");
                                         DebugText(to_string(carrier.size()));
                                         continue;
                                     }
                                 }
                        }


                            //补充石头
                            if(info.Stone<=BUILDING_MARKET_STONE_UPGRADE_STONE && stats.stone<2){
                                tagResource* neareststone = findNearestResource(info.resources,RESOURCE_STONE, idleFarmer->DR,idleFarmer->UR);
                                HumanAction(idleFarmer->SN,neareststone->SN);
                                stats.stone++;
                                continue;
                            }

                            //继续砍树
                            if(idleFarmer){
                                tagResource* nearesttree = findOptimalResource(info.resources, {RESOURCE_TREE}, idleFarmer->DR,idleFarmer->UR,2);
                                HumanAction(idleFarmer->SN,nearesttree->SN);
                                continue;
                            }

                        }

                    }

                    // 建造渔船
                    for (tagBuilding& building : info.buildings) {
                        if (building.Type == BUILDING_DOCK && building.Project == 0 &&
                            info.Wood >= BUILDING_DOCK_CREATE_SAILING_WOOD && stats.totalboat<6 && stats.transboat>0) {
                            BuildingAction(building.SN, BUILDING_DOCK_CREATE_SAILING);
                            break;
                        }
                    }



                   //船坞建造运输船（要改）
                    for (tagBuilding& building : info.buildings) {
                        if(locktrans){
                            break;
                        }
                        if (building.Type == BUILDING_DOCK && building.Project == 0 &&
                            info.Wood >= BUILDING_DOCK_CREATE_WOOD_BOAT_WOOD && stats.transboat<1 && !locktrans) {
                            BuildingAction(building.SN, BUILDING_DOCK_CREATE_WOOD_BOAT);
                            break;
                        }

                    }
                    if(stats.transboat>1 && !locktrans){
                        for(tagFarmer ship: info.farmers){
                            if(ship.FarmerSort==1){
                                locktrans=true;
                                break;

                            }
                        }
                    }



                    //差不多海岸探索结束，派人（出现没探完就来的情况）
                    if(findenemyland && enemyLandCoords.size()>50 && info.GameFrame%20==0 && !beizhan && (tempt_doing || !escape_tran)){
                    for(tagFarmer s:info.farmers){
                        if(s.SN==transn && s.NowState==HUMAN_STATE_IDLE){
                            if(s.Resource==3){
                                //提前清理，避免重复计数
                                carrier.clear();
                                auto pair= getAnyMiddleCoastBlock(coastline);
                                DebugText("启程"+to_string(startdr)+' '+to_string(startur));
                                int dr,ur;
                                if(pair.first!=-1 && findCoastNearTransport(info,pair.first,pair.second,dr,ur,ddr,dur)){
                                    static double sdr=(dr+0.5)*BLOCKSIDELENGTH,sur=(ur+0.5)*BLOCKSIDELENGTH;
                                    enddr=dr,endur=ur;
                                     if(s.DR==sdr&&s.UR==sur&&s.Resource==3 && info.GameFrame%20==0){
                                         DebugText("逐渐靠岸");
                                         sdr+=2*ddr;
                                         sur+=2*dur;
                                         HumanMove(transn,sdr,sur);
                                     }
                                      HumanMove(transn,sdr,sur);
                                }
                            }
                        }
                    }

                    }

                    if(stats.totalfarm<=farmermax-3&&kaoan){
                        qicheng=true;
                    }


                 //找到合适的地点建造兵营...

                    for(tagFarmer dis:info.farmers){
                                if(!InenemyLand(dis.BlockDR,dis.BlockUR)){
                                    continue;
                                }
                                if(dis.FarmerSort!=0){
                                    continue;
                                }


                                if(dis.NowState==HUMAN_STATE_IDLE){
                                    //建马厩
                                    if(getBuildingCount(BUILDING_STABLE)<1){
                                           int tdr,tur;
                                           if(armycampdone){
                                               if(findValidBuildLocation(info, BUILDING_STABLE,dis.BlockDR,dis.BlockUR,tdr,tur) && info.Wood>=BUILD_STABLE_WOOD){
                                                   HumanBuild(dis.SN,BUILDING_STABLE,tdr,tur);
                                                   break;
                                               }
                                           }
                                       }


                                    //箭塔
                                     if(getBuildingCount(BUILDING_ARROWTOWER)<1 && arrow_up){
                                            int tdr,tur;
                                                if(findValidBuildLocation(info, BUILDING_ARROWTOWER,dis.BlockDR,dis.BlockUR,tdr,tur) && info.Stone>=BUILD_ARROWTOWER_STONE){
                                                        HumanBuild(dis.SN,BUILDING_ARROWTOWER,tdr,tur);
                                                        break;
                                                }

                                    }

                                     tagResource* nearestgold=findNearestResource(info.resources,RESOURCE_GOLD,dis.DR,dis.UR);
                                     if(getBuildingCount(BUILDING_STOCK)<3 && nearestgold &&info.Wood>=BUILD_STOCK_WOOD && armycampdone &&getBuildingCount(BUILDING_STABLE)>0){
                                         int cdr,cur;
                                         if(findValidBuildLocation(info,BUILDING_STOCK,nearestgold->BlockDR,nearestgold->BlockUR,cdr,cur)){
                                             HumanBuild(dis.SN,BUILDING_STOCK,cdr,cur);
                                             break;
                                         }
                                     }

                                     if(getBuildingCount(BUILDING_STOCK)>=3  && beizhan){
                                         if(nearestgold){
                                             HumanAction(dis.SN,nearestgold->SN);
                                             continue;
                                         }

                                      }




                                 //找地方
                                 if(getBuildingCount(BUILDING_STABLE)<1 && info.GameFrame%20==0 && armycampdone){
                                     auto blackGrids = findNearbyBlackGrids(info,enemyLandCoords,4);
                                     if (blackGrids.empty()) break;
                                     // 找黑格子附近的可移动海格子
                                     auto target = findWaternearBlack(info, blackGrids,dis);
                                     if (target.first == -1){
                                         break;
                                     }
                                     //移动战船
                                     if (dis.NowState == HUMAN_STATE_IDLE) {
                                     HumanMove(dis.SN,(target.first+0.5)*BLOCKSIDELENGTH, (target.second+0.5)*BLOCKSIDELENGTH);
                                     continue;
                                     }

                                 }

                                 //返回运输船
                                 if(getBuildingCount(BUILDING_STABLE)>0  && !tempt_doing){
                                     HumanAction(dis.SN,transn);
                                     escape_tran=true;
                                 }

                                 }

                            }


                    //升级技术
                    for(tagBuilding build:info.buildings){
                        if(build.Project!=0||build.Percent<100){
                            continue;
                        }

                        if (build.Type == BUILDING_GRANARY  && info.Meat >= BUILDING_GRANARY_ARROWTOWER_FOOD && !arrow_up) {
                            BuildingAction(build.SN, BUILDING_GRANARY_ARROWTOWER);
                            DebugText("升级箭塔");
                            arrow_up=true;
                            break;
                        }
                        if(build.Type==BUILDING_STOCK){
                            if(info.Meat>=BUILDING_STOCK_UPGRADE_USETOOL_FOOD && !upgrade_tool){
                                BuildingAction(build.SN,BUILDING_STOCK_UPGRADE_USETOOL);
                                DebugText("工具升级");
                                upgrade_tool=true;
                                break;
                            }

                            if(upgrade_tool){

                                if(info.Meat>= BUILDING_STOCK_UPGRADE_DEFENSE_RIDER_FOOD && !upgrade_riderdef){
                                    BuildingAction(build.SN,BUILDING_STOCK_UPGRADE_DEFENSE_RIDER);
                                    DebugText("骑兵护甲");
                                    upgrade_riderdef=true;
                                    break;
                                }

                            }

                        }

                    }


                    //暴兵流
                    if(armystats.total<30 ){
                    for(tagBuilding camp : info.buildings){

                        if(camp.Type==BUILDING_STABLE && camp.Project==0 && armystats.scout<8){
                            if(info.Meat>=BUILDING_STABLE_CREATE_SCOUT_FOOD){
                                BuildingAction(camp.SN,BUILDING_STABLE_CREATE_SCOUT);
                                continue;
                            }
                        }
                    }
                    }

                    //诱杀流
                    vector<int>scoutsn;
                    for(tagArmy scout:info.armies){
                        if(scout.Sort==AT_SCOUT && scout.Blood>0){
                            scoutsn.push_back(scout.SN);
                        }
                    }



                    if(armystats.scout>0 && !tempt_done){
                        for(tagArmy scout:info.armies){
                            if(scout.Sort==AT_SCOUT && !tempt_doing){
                                auto it=find(scoutsn.begin(),scoutsn.end(),activeScoutSN);
                                if(it==scoutsn.end() ){
                                    activeScoutSN=scout.SN;
                                    tempt=false;
                                    tempt_count++;
                                    break;
                                }
                            }
                        }
                    }

                    //探索
                    if(!tempt && armystats.scout>0 && !tempt_doing){
                        tempt_begin=true;
                        for(tagArmy scout:info.armies){
                            if(scout.Sort==AT_SCOUT && scout.SN==activeScoutSN){
                                for(tagArmy& enemy : info.enemy_armies){
                                    if(enemy.WorkObjectSN==activeScoutSN){
                                        tempt=true;
                                        DebugText("诱敌成功");
                                        HumanMove(scout.SN,(tempdr+0.5)*BLOCKSIDELENGTH,(tempur+0.5)*BLOCKSIDELENGTH);
                                        DebugText(to_string(tempdr)+','+to_string(tempur));
                                        break;
                                    }
                                }
                                if(tempt){
                                    break;
                                }

                                 bool move=false;
                                 if(info.GameFrame%15==0 && scout.NowState==HUMAN_STATE_IDLE){
                                        bool move=false;
                                        for(int i=0;i<128;i+=7){
                                            for(int j=0;j<128;j+=7){
                                                if(InenemyLand(i,j) && visited[i][j]==false && mapGrid[i][j]<=4 && mapGrid[i][j]>=0 ){
                                                  move=true;
                                                  HumanMove(activeScoutSN,(i+0.5)*BLOCKSIDELENGTH,(j+0.5)*BLOCKSIDELENGTH);
                                                  visited[i][j]=true;
                                                  break;
                                                }
                                            }
                                            if(move){
                                                break;
                                            }
                                        }
                                }

                            }
                        }
                    }

                    //诱惑到岸边
                    vector<int> shipsn;
                    for(tagArmy& ship:info.armies){
                        if(ship.Sort==AT_SHIP){
                            shipsn.push_back(ship.SN);
                        }
                    }


                    //战舰提前到场
                    if(tempt_begin && !tempt_doing && !enemy_army_ship && !tempt_accident){
                        for(tagArmy ship:info.armies){
                            //到达诱惑地点
                            if(ship.Sort==AT_SHIP && ship.NowState==HUMAN_STATE_IDLE){
                                    int tagdr=0,tagur=0,wdr,wur;
                                   if(findCoastNearTransport(info,tempdr,tempur,tagdr,tagur,wdr,wur)){
                                       HumanMove(ship.SN,(tagdr+0.5-1*wdr)*BLOCKSIDELENGTH,(tagur+0.5-1*wur)*BLOCKSIDELENGTH);
                                       continue;

                            }
                        }

                    }

                    }

                    //在视野中诱惑
                    if(enemy_army!=nullptr && !tempt_doing){
                        for(tagArmy& enemy : info.enemy_armies){
                            if(enemy.Sort!=AT_SHIP && enemy.Blood>0 && InenemyLand(enemy.BlockDR,enemy.BlockUR)){
                                auto it=find(shipsn.begin(),shipsn.end(),enemy.WorkObjectSN);
                                if(it!=shipsn.end()){
                                    tempt_doing=true;
                                    if(!tempt_begin){
                                        tempt_accident=true;
                                    }
                                    DebugText("战舰诱惑到敌人了");
                                }
                            }
                        }
                    }
                    if(enemy_army!=nullptr && !escape_tran_2 && !tempt_accident){
                        for(tagArmy& enemy : info.enemy_armies){
                            if(enemy.Sort!=AT_SHIP && enemy.Blood>0 && InenemyLand(enemy.BlockDR,enemy.BlockUR) && enemy.WorkObjectSN==transn){
                                for(tagArmy& ship:info.armies){
                                    if(ship.Sort==AT_SHIP && ship.Blood>0){
                                        HumanMove(transn,(ship.BlockDR+0.5)*BLOCKSIDELENGTH,(ship.BlockUR+0.5)*BLOCKSIDELENGTH);
                                        escape_tran=true;
                                        escape_tran_2=true;
                                        tempt_doing=true;
                                        break;
                                    }
                                }

                            }
                        }
                    }
                    //农民被开
                    if(!tempt_begin && !tempt_accident && !enemy_army_ship){
                        for(tagFarmer farmer :info.farmers){
                            for(tagArmy enemy:info.enemy_armies){
                                if(enemy.WorkObjectSN==farmer.SN ){
                                    tempt_accident=true;
                                    tempt_doing=true;
                                    break;
                                }
                            }
                        }
                    }


                    //意外堵门
                    if(tempt_begin && tempt_count>=2 &&!tempt_doing){
                        tempt_doing=true;
                        tempt_accident=true;
                    }

                    //人数太少，出现意外
                    if(tempt_doing && armystats.ship<6){
                        tempt_accident=true;
                    }

                    //诱杀时刻
                    if(tempt_doing){
                        for(tagArmy& ship:info.armies){
                            if(ship.NowState==HUMAN_STATE_IDLE && ship.Sort==AT_SHIP){
                                int enemy_sn=0;
                                for(tagArmy& enemy : info.enemy_armies){
                                    int dist=abs(ship.BlockDR-enemy.BlockDR)+abs(ship.BlockUR-enemy.BlockUR);
                                    if(dist<=15 && enemy.Blood>0 && !tempt_accident && enemy.Blood>0){
                                        enemy_sn=enemy.SN;
                                        break;
                                    }
                                    if(tempt_accident_deal && tempt_accident_ship[ship.SN]==true && dist<=15 && enemy.Blood>0){
                                        enemy_sn=enemy.SN;
                                        break;
                                    }
                                }
                                HumanAction(ship.SN,enemy_sn);

                            }
                        }
                    }

                 //战舰前往事故地点
                    if(tempt_accident){
                        tempt_accident_deal=true;
                        for(tagArmy& ship:info.armies){
                            if(ship.Sort==AT_SHIP ) {
                                marktemptship(ship.SN);
                            }
                        }
                        for(tagArmy& ship:info.armies){
                            if(ship.Sort==AT_SHIP && tempt_accident_ship[ship.SN]==false && ship.NowState==HUMAN_STATE_IDLE){
                               int dr=0,ur=0;
                               for(tagArmy& enemy : info.enemy_armies){
                                   if(enemy.Sort!=AT_SHIP && InenemyLand(enemy.BlockDR,enemy.BlockUR)){
                                       dr=enemy.BlockDR;
                                       ur=enemy.BlockUR;
                                       break;
                                   }
                               }
                               //到达诱惑地点
                               int tagdr=0,tagur=0,wdr,wur;
                              if(findCoastNearTransport(info,dr,ur,tagdr,tagur,wdr,wur)){
                                  HumanMove(ship.SN,(tagdr+0.5-1*wdr)*BLOCKSIDELENGTH,(tagur+0.5-1*wur)*BLOCKSIDELENGTH);
                                  tempt_accident_ship[ship.SN]=true;
                                  DebugText(to_string(ship.SN)+"前往事故地点");
                                  continue;

                               }


                            }
                        }

                    }

                    static vector<int> ship_kill_num;

                    //战舰击杀数
                    if(tempt_doing && !enemy_army_ship){
                        for(tagArmy& ship:info.armies){
                            if(find(ship_kill_num.begin(),ship_kill_num.end(),ship.WorkObjectSN)==ship_kill_num.end() && ship.Sort==AT_SHIP){
                                ship_kill_num.push_back(ship.WorkObjectSN);
                            }
                        }
                    }




                    if(tempt_doing && !tempt_done){
                        if(ship_kill_num.size()>=22){
                            escape_tran=false;
                            tempt_cool_time++;
                        }

                        if(tempt_cool_time>=50 && !enemy_army){
                            tempt_done=true;
                        }
                    }




                     // 战争开始(实际推塔)
                     if(tempt_done && !beizhan){
                         beizhan=true;
                         DebugText("战争开始");
                     }



                     //升级采矿
                     for(tagBuilding market :info.buildings){
                         if(!upgrade_gold && market.Type==BUILDING_MARKET && market.Project == 0 && info.Meat>=BUILDING_MARKET_GOLD_UPGRADE_FOOD &&info.Wood>=BUILDING_MARKET_GOLD_UPGRADE_WOOD){
                             BuildingAction(market.SN,BUILDING_MARKET_GOLD_UPGRADE);
                             DebugText("升级采金");
                             upgrade_gold=true;
                             break;
                         }
                     }

                     //第四阶段判断
                     if(beizhan && armystats.total>0 && enemy_building==nullptr ){

                     //记录金矿数量变化
                     if(info.GameFrame%10==0 && !find_gold){
                         int goldnum=0;
                         for(tagResource gold:info.resources){
                             if(gold.Type==RESOURCE_GOLD){
                                 goldnum++;
                             }
                         }
                         if(goldnum>13){
                             find_gold=true;
                             DebugText("找到大量的金矿");
                         }
                     }

                     if(beizhan && find_gold &&enemysn.size()>=20 && enemybuildsn.size()>2 ){
                             noenemyframe++;
                             if(noenemyframe>=60 ){
                             stage4=true;
                             DebugText("第四阶段");

                         }

                     }


                }

          }


         //第四阶段
                if(stage4){
                        for(tagArmy army :info.armies){
                            if(armystats.total>8){
                                HumanAction(army.SN,army.SN);
                                armystats.total--;
                                continue;
                            }

                            }



                    //造人
                        if(upgrade_gold){
                            for (tagBuilding& building : info.buildings) {
                                if (building.Type == BUILDING_CENTER && building.Project == 0 &&
                                    info.Meat >= BUILDING_CENTER_CREATEFARMER_FOOD && upgrade_gold &&
                                    stats.total < 50) {
                                    BuildingAction(building.SN, BUILDING_CENTER_CREATEFARMER);
                                    break;
                                }
                            }
                        }


                    //升级采矿
                        if(!upgrade_gold){
                            for(tagBuilding market :info.buildings){
                                if( market.Type==BUILDING_MARKET && market.Project == 0 && info.Meat>=BUILDING_MARKET_GOLD_UPGRADE_FOOD &&info.Wood>=BUILDING_MARKET_GOLD_UPGRADE_WOOD){
                                    BuildingAction(market.SN,BUILDING_MARKET_GOLD_UPGRADE);
                                    DebugText("升级采金");
                                    upgrade_gold=true;
                                    break;
                                }
                            }
                        }



                    //安排村民
                    for(tagFarmer idleFarmer:info.farmers){
                        //我方大陆
                        if(idleFarmer.FarmerSort!=0){
                            continue;
                        }
                        if(idleFarmer.Blood<1){
                            continue;
                        }
                        if(!(InenemyLand(idleFarmer.BlockDR,idleFarmer.BlockUR)) ){
                            if(idleFarmer.WorkObjectSN!=transn && info.GameFrame%10==0 &&  upgrade_gold && !goldminer){
                                auto it=find(carrier.begin(),carrier.end(),idleFarmer.SN);


                                 if(shifasite && carrier.size()<5){
                                     HumanAction(idleFarmer.SN,transn);
                                     auto it=find(carrier.begin(),carrier.end(),idleFarmer.SN);
                                     if(it!=carrier.end()){
                                         continue;
                                     }
                                     else{
                                         carrier.push_back(idleFarmer.SN);
                                         DebugText(to_string(idleFarmer.SN));
                                         DebugText("上船");
                                         DebugText(to_string(carrier.size()));
                                         continue;
                                         }
                                 }

                                 if(it!=carrier.end()){
                                         HumanAction(idleFarmer.SN,transn);
                                         continue;
                                     }
                            }

                            if(idleFarmer.NowState==HUMAN_STATE_IDLE && upgrade_gold && goldminer){
                                //建农场
                                if(getBuildingCount(BUILDING_FARM)<2 &&info.Wood>BUILD_FARM_WOOD && getBuildingCount(BUILDING_STOCK)>4){
                                    int farmdr,farmur;
                                    //在市中心或谷仓附近建农田
                                    if (findValidBuildLocation(info, BUILDING_FARM,centersite.BlockDR,centersite.BlockUR,farmdr,farmur )||
                                            findValidBuildLocation(info, BUILDING_FARM,gucang.BlockDR,gucang.BlockUR,farmdr,farmur )) {
                                        HumanBuild(idleFarmer.SN, BUILDING_FARM, farmdr,farmur);
                                        DebugText("建造农场");
                                        continue;
                                    }
                                }
                                //砍树
                                tagResource* neartree=findNearestResource(info.resources,RESOURCE_TREE,idleFarmer.DR,idleFarmer.UR);
                                HumanAction(idleFarmer.SN,neartree->SN);
                                continue;

                            }

                        }



                       //敌方大陆开金矿
                       if( InenemyLand(idleFarmer.BlockDR,idleFarmer.BlockUR)){

                            ResourceDensity denseArea = findMostDenseArea(info, RESOURCE_GOLD, 10);
                           // 寻找金矿资源最密集的区域，建造2间仓库
                           if(getBuildingCount(BUILDING_STOCK)<6 && info.Wood>= BUILD_STOCK_WOOD){
                               int tagdr=0,tagur=0;
                               if (denseArea.density > 0) { // 找到有效密集区域
                                   if(findValidBuildLocation(info,BUILDING_STOCK,denseArea.centerDR,denseArea.centerUR,tagdr,tagur)){
                                       HumanBuild(idleFarmer.SN,BUILDING_STOCK,tagdr,tagur);
                                       break;
                                   }
                               }
                           }

                           if(idleFarmer.NowState==HUMAN_STATE_IDLE){
                               auto goldSNs = GetNearbyOuterGoldSNs(denseArea.centerDR,denseArea.centerUR,30,info);
                               int gold_num=goldSNs.size();
                               static int goldernum=0;
                               if(!goldSNs.empty()){
                                   HumanAction(idleFarmer.SN,goldSNs[goldernum%gold_num]);
                                   goldernum++;
                               }
                           }

                       }


                    }




                }



                //记录最大的村民的总数，用来判断登录敌方大陆
                if(farmermax<stats.totalfarm){
                    farmermax=stats.totalfarm;
                }

    return;
}
